import NProgress from "nprogress";
import 'nprogress/nprogress.css'
import getPageTitle from "@/utils/get-current-page-title";
import {getToken} from "@/utils/verifyToken";
import store from "@/store";
import {ElMessage, ElMessageBox} from "element-plus";
import router, {asyncRoutes, resetRouter} from "@/router";
import {isAccess} from "@/utils/access";
NProgress.configure({
  easing: 'ease',// 动画方式
  speed: 500, // 递增进度条的速度
  trickleSpeed: 200, // 自动递增间隔
  showSpinner:false,// 配置禁用小圆环
  minimum: 0.3, // 初始化时的最小百分比
}) // NProgress 配置

//前置路由守卫，对即将前往的路由做权限校验
router.beforeEach(async(to, from, next) => {
  // 开始进度条
  NProgress.start()
  if (to.path==='/NoRoute/logout'){
    // from.path='/homepage'
    next('/homepage')
    return true
  }
  if (to.path==='/404' || to.path==='/403' || to.path==='/warning'){
    next()
    return true
  }
  // 确定用户是否已登录
  const hasToken = getToken()
  //如果用户登录
  if (hasToken) {
    //如果登录，且将去到登录页，则进行从定向到主页
    if (to.path === '/login') {
      // 如果已登录，则重定向到主页
      next({path: '/'})
      // NProgress.done() //结束进度条
    } else {
      // 通过getters判断用户是否获得了权限角色
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      //如果角色存在，可以成功跳转
      if (hasRoles) {
        /*if (store.getters.roles.includes('admin') &&getDevice()){
          next('/warning')
        }
        else */if(to.matched.length===0){
          next('/404')
        }
        else {
          if (to.matched.some(record =>record.meta.hasOwnProperty('path'))){
            next()
          }

          else
            next('/404')
        }
      } else {
        try {
          // 角色不存在，则获取用户信息
          const {roles} = await store.dispatch('user/getUserInfo')
          //根据角色动态生成可访问路由
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
          accessRoutes.forEach(rt => {
            router.addRoute(rt)})
          //设置replace: true，这样导航就不会留下历史记录
          if (roles.indexOf('user')!==-1){
            resetRouter('admin')
          }else {
            resetRouter('user')
          }
          next({...to, replace: true})

        } catch (error) {
          console.log(error)
          // 删除令牌，进入登录页面重新登录
          await store.dispatch('user/resetToken')
          ElMessage.error(error || '本次登录发生错误，请重新登录')
          next(`/login?redirect=${to.fullPath}`)
        }
      }
    }
  }
  //如果用户没登录，生成guest用户的访问路由(默认角色guest)
  else {
    await store.dispatch('user/resetToken')
    if(/login[? .a-zA-Z]*/.test(to.path) ||to.path==='/homepage'){
      next()
      return
    }
    //如果没匹配到分两种种情况1.匹配asyncRoutes路由,2.未匹配到
    isAccess(to.path,asyncRoutes)
    //如果匹配到则需要权限访问
    if(store.getters.access){
      //弹框
      await ElMessageBox.confirm("您当前未处于登录状态，请先登录", '提示',{
        distinguishCancelAndClose: true,
        confirmButtonText: '登录',//确定按钮
        cancelButtonText: '取消',//取消按钮
        lockScroll:true,//出现box时锁定滚动框
        type:'warning'//消息类型
      })
          .then(()=>{
            next(`/login?redirect=${to.fullPath}`)
          })
          .catch(()=>{
              if (to.path!==from.path)
                next(from.path)
              else{
                next('/homepage')
              }
          })
    }else if (to.matched.length>0){
      next()
      return true
    }
    else {
      next('/404')
    }
  }
})
router.afterEach((to,from) => {
  sessionStorage.setItem("path",to.path)
  store.dispatch('access/setAccess', false).then()
  // 设置页面标题
  document.title = getPageTitle(to.meta.title)
  // 结束进度条
  NProgress.done()
})


